import 'dart:async';
import 'dart:ffi';
import 'dart:math';

import 'package:card_topia/design_specifications.dart';
import 'package:ficonsax/ficonsax.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

///对应文章解析  https://juejin.cn/post/7124064789763981326
class TouchCard extends StatefulWidget {
  const TouchCard({Key? key, required this.frontChild, required this.backChild, required this.cardWidth, required this.cardHeight}) : super(key: key);
  final Widget frontChild;
  final Widget backChild;
  final double cardWidth;
  final double cardHeight;
  @override
  State<TouchCard> createState() => _TouchCardState();
}

class _TouchCardState extends State<TouchCard> {

  bool startTransform = true;
  double _distance = 0;
  var showIndex = 1;

  Timer? timer;
  double currentDx = 0;
  double endX = 0;
  bool is3D = true;
  @override
  void initState() {
    super.initState();
    autoShow();
  }

  @override
  void dispose() {
    super.dispose();
    if (timer?.isActive == true) {
      timer?.cancel();
    }
  }

  cancelShow() {
    if (timer?.isActive == true) {
      timer?.cancel();
    }
    if(mounted){
      _distance = 0;
      is3D = false;
      setState(() {

      });
    }
  }

  autoShow() {
    cancelShow();
    is3D = true;
    startTransform = true;
    if(timer?.isActive??false){
      return;
    }
    timer = Timer.periodic(const Duration(milliseconds: 25), (t) {
      if(_distance<widget.cardWidth) {
        _distance = _distance + 1;
      }
      if(_distance>widget.cardWidth){
        t.cancel();
        reverse();
      }
      setState(() {});
    });

  }
  reverse(){
    timer = Timer.periodic(const Duration(milliseconds: 25), (t) {
      if(_distance>-widget.cardWidth) {
        _distance = _distance - 1;
      }
      if(_distance ==0){
        t.cancel();
        is3D = false;
      }
      setState(() {});
    });
  }
  //循环展示
  loopShow(){
    _distance = 0;
    is3D = true;
    bool right = true;
    if(timer?.isActive??false){
      return;
    }
      timer = Timer.periodic(const Duration(milliseconds: 25), (t) {
        if(_distance<widget.cardWidth&&right){
          _distance = _distance + 1;
        }else{
          _distance = _distance -1;
        }
        if(_distance>widget.cardWidth){
          right = false;
        }else if(_distance<-widget.cardWidth){
          right = true;
        }

        setState(() {});
      });
  }
  @override
  Widget build(BuildContext context) {
    if(-_distance<widget.cardWidth/2&&-_distance>-widget.cardWidth/2){
      showIndex = 1;
    }else{
      showIndex = 0;
    }
    return Stack(
      alignment: Alignment.topCenter,
      children: [
        //高度
        Container(height: widget.cardHeight+32.w),
        //展台
        Positioned(
          top: 360.w,
          left: 0,
          right: 0,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Container(
                // margin: EdgeInsets.symmetric(horizontal: 16.w),
                child: Image.asset("assets/card_plant.png",),),
              Positioned(
                  top: 16.w,
                  child: Image.asset("assets/shadow.png")),
              Positioned(
                  top: 105.w,
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      //Indicator
                      AnimatedPositioned(
                        curve: Curves.easeInOut,
                        duration: const Duration(milliseconds: 100),
                        left: is3D?0:85.w,
                        child: Container(
                          width: 85.w,
                          height: 24.w,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(50)
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 24.w,
                        width: 170.w,
                        child: Row(
                          children: [
                            InkWell(
                              onTap: ()=>loopShow(),
                              child: SizedBox(
                                width: 85.w,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(IconsaxOutline.play_cricle,color: is3D?textColor:Colors.white,size: 14.w,),
                                    SizedBox(width: 8.w,),
                                    Text("3D展示",style: TextStyle(fontSize: 12.sp,color: is3D?textColor:Colors.white,fontFamily: harmony),)
                                  ],
                                ),
                              ),
                            ),
                            InkWell(
                              onTap: ()=>cancelShow(),
                              child: SizedBox(
                                width: 85.w,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(IconsaxOutline.monitor,color: is3D?Colors.white:textColor,size: 14.w,),
                                    SizedBox(width: 8.w,),
                                    Text("平面展示",style: TextStyle(fontSize: 12.sp,color: is3D?Colors.white:textColor,fontFamily: harmony),)
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      )
                    ],
                  ))
            ],
          ),
        ),
        //卡片
        Positioned(
          top: 24.w,
          child: GestureDetector(
            onHorizontalDragStart: (_){
              is3D = true;
            },
            // onTapDown: (_){
            //   cancelShow();
            // },
            onHorizontalDragUpdate: (detail){
              // if(detail.localPosition.dx is Double){
              //   return;
              // }
              // if(detail.localPosition.dx %2==0){
              //   return;
              // }
              if(detail.localPosition.dx>0&&detail.localPosition.dx<widget.cardWidth){
                setState(() {
                    var right = _distance+(2*pi)>widget.cardWidth?widget.cardWidth:_distance+(2*pi);
                    var left = _distance-(2*pi)<-widget.cardWidth?-widget.cardWidth:_distance-(2*pi);
                    _distance = detail.delta.dx>0?right:left;
                });
              }

            },
            child: Container(
              color: Colors.transparent,
              child: Transform(
                transform: Matrix4.identity()
                  ..setEntry(3, 2, 0.001)
                // ..rotateX(startTransform ? touchY : 0.0)
                  ..rotateY(startTransform ? -(_distance/widget.cardWidth)*pi: 0.0),
                alignment: FractionalOffset.center,
                child: IndexedStack(
                  index: showIndex,
                  children: [
                    widget.backChild,
                    widget.frontChild
                  ],
                ),
              ),
            ),
          ),
        ),

        // Slider(value: _distance,max: widget.cardWidth,min: 0, onChanged: (value){
        //   setState(() {
        //     _distance = value;
        //   });
        // })
      ],
    );
  }
}